
from flask import jsonify, request
from flask_login import current_user
from flask_restful import Resource, marshal_with, reqparse  # type: ignore
from controllers.errors.emoji_errors import HTTPEmojiCreateParamError, HTTPEmojiNotExistError, HTTPEmojiPackCreateParamError, HTTPEmojiPackNotExistError
from core.roles.role_check import check_perms
from libs.helper import extract_remote_ip
from libs.login import login_required
from controllers.console import api
from models.robot.rob_emoji import EmojiType
from services.errors.emoji import EmojiCreatePrameterError, EmojiNotExistError, EmojiPackCreatePrameterError, EmojiPackageNotExistError
from services.robot.emoji_service import EmojiService
from fields.emoji_pack_fields_def import base_emoji_pack_fields,emoji_list_fields,emoji_fields,emoji_pack_list_fields
from werkzeug.exceptions import BadRequest

class EmojiManangeApi(Resource):
    @login_required
    @check_perms(perms=['emoji:list'])
    @marshal_with(emoji_list_fields)
    def get(self):
        argparser = reqparse.RequestParser()
        argparser.add_argument("id",type=str,required=False,location='args')
        argparser.add_argument("name",type=str,required=False,location='args')
        argparser.add_argument("emoji_code",type=str,required=False,location='args')
        argparser.add_argument("emoji_type",type=str, required=False,default=None,location='args')
        argparser.add_argument("emoji_pack_id",type=str,required=False,location='args')
        argparser.add_argument("page",type=int,required=False,default=-1,location='args')
        argparser.add_argument("page_size",type=int,required=False,default=-1,location='args')
        args = argparser.parse_args()
        return EmojiService.get_emoji_list(current_user.current_tenant_id,args)
    
    @login_required
    @check_perms(perms=['emoji:new'])
    @marshal_with(emoji_fields)
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument("name",type=str,required=True,location='json')
        parser.add_argument("descrip",type=str,required=False,location='json')
        parser.add_argument("emoji_code",type=str,required=True,location='json')
        parser.add_argument("emoji_map",type=str,action="append",required=False,location='json')
        parser.add_argument("emoji_type",type=str,choices=EmojiType.choices(), required=True,location='json')
        parser.add_argument("emoji_pack_id",type=str,required=True,location='json')
        parser.add_argument("file_id",type=str,required=False,location='json')
        parser.add_argument("file_url",type=str,required=False,location='json')
        args = parser.parse_args()
        try:
            emoji =  EmojiService.create_emoji(current_user,args,extract_remote_ip(request))
            return emoji
        except EmojiPackageNotExistError as e:
            raise HTTPEmojiPackNotExistError(emoji_pack_id=e.emoji_pack_id)
        except EmojiCreatePrameterError as e:
            raise HTTPEmojiCreateParamError(message=e.description)
        except Exception as e:
            raise BadRequest(description=str(e))
        
    @login_required
    @check_perms(perms=['emoji:update'])
    @marshal_with(emoji_fields)
    def put(self):
        parser = reqparse.RequestParser()
        parser.add_argument("id",type=str,required=True,location='json')
        parser.add_argument("name",type=str,required=True,location='json')
        parser.add_argument("descrip",type=str,required=False,location='json')
        parser.add_argument("emoji_code",type=str,required=True,location='json')
        parser.add_argument("emoji_type",type=str,choices=EmojiType.choices(), required=True,location='json')
        parser.add_argument("emoji_map",type=str,action="append",required=False,location='json')
        parser.add_argument("file_id",type=str,required=False,location='json')
        parser.add_argument("file_url",type=str,required=False,location='json')
        args = parser.parse_args()
        try:
            emoji =  EmojiService.update_emoji(current_user,args,extract_remote_ip(request))
            return emoji
        except EmojiNotExistError as e:
            raise HTTPEmojiNotExistError(emoji_id=e.description)
        except EmojiCreatePrameterError as e:
            raise HTTPEmojiCreateParamError(message=e.description)
        except Exception as e:
            raise BadRequest(description=str(e))
        
    @login_required
    @check_perms(perms=['emoji:del'])
    def delete(self):
        argparser = reqparse.RequestParser()
        argparser.add_argument("id",type=str,required=True,location='json')
        args = argparser.parse_args()
        emoji_id = args.get("id",None)
        if not emoji_id:
            raise HTTPEmojiCreateParamError(message="emoji_id is required")
        try:
            EmojiService.del_emoji(current_user,emoji_id,extract_remote_ip(request))
            return jsonify(
                {
                    "code": 200,
                    "status": "success",
                }
            )
        except EmojiNotExistError as e:
            raise HTTPEmojiNotExistError()
        except Exception as e:
            raise BadRequest(description=str(e))
        
class EmojiPackManageApi(Resource):
    @login_required
    @check_perms(perms=['emoji_pack:list'])
    @marshal_with(emoji_pack_list_fields)
    def get(self):
        argparser = reqparse.RequestParser()
        argparser.add_argument("id",type=str,required=False,location='args')
        argparser.add_argument("name",type=str,required=False,location='args')
        argparser.add_argument("page",type=int,required=False,default=-1,location='args')
        argparser.add_argument("page_size",type=int,required=False,default=-1,location='args')
        args = argparser.parse_args()
        return EmojiService.get_emoji_pack_list(current_user.current_tenant_id,args)
    
    @login_required
    @check_perms(perms=['emoji_pack:new'])
    @marshal_with(base_emoji_pack_fields)
    def post(self):
        argparser = reqparse.RequestParser()
        argparser.add_argument("name",type=str,required=True,location='json')
        argparser.add_argument("agent_id",type=str,required=False,location='json')
        argparser.add_argument("descrip",type=str,required=True,location='json')
        argparser.add_argument("price",type=float,required=False,location='json')
        args = argparser.parse_args()
        try:
            pack =  EmojiService.create_emoji_pack(current_user,args,extract_remote_ip(request))
            return pack
        except EmojiPackCreatePrameterError as e:
            raise HTTPEmojiPackCreateParamError(message=e.description)
        except Exception as e:
            raise BadRequest(description=str(e))
        
    @login_required
    @check_perms(perms=['emoji_pack:update'])
    @marshal_with(base_emoji_pack_fields)
    def put(self):
        argparser = reqparse.RequestParser()
        argparser.add_argument("id",type=str,required=True,location='json')
        argparser.add_argument("name",type=str,required=True,location='json')
        argparser.add_argument("agent_id",type=str,required=False,location='json')
        argparser.add_argument("descrip",type=str,required=True,location='json')
        argparser.add_argument("price",type=float,required=False,location='json')
        args = argparser.parse_args()
        try:
            pack =  EmojiService.update_emoji_pack(current_user,args,extract_remote_ip(request))
            return pack
        except EmojiPackageNotExistError as e:
            raise HTTPEmojiPackNotExistError(emoji_pack_id=e.emoji_pack_id)
        except Exception as e:
            raise BadRequest(description=str(e))
        
    @login_required
    @check_perms(perms=['emoji_pack:del'])
    def delete(self):
        argparser = reqparse.RequestParser()
        argparser.add_argument("id",type=str,required=True,location='json')
        args = argparser.parse_args()
        emoji_pack_id = args.get("id",None)
        if not emoji_pack_id:
            raise HTTPEmojiCreateParamError(message="emoji_id is required")
        try:
            EmojiService.del_emoji_pack(current_user,emoji_pack_id,extract_remote_ip(request))
            return jsonify(
                {
                    "code": 200,
                    "status": "success",
                }
            )
        except EmojiPackageNotExistError as e:
            raise HTTPEmojiPackNotExistError(emoji_pack_id=e.emoji_pack_id)
        except Exception as e:
            raise BadRequest(description=str(e))
        
    
class EmojiMapsApi(Resource):
    @login_required
    @check_perms(perms=['emoji:list'])
    def get(self,emoji_pack_id:str):
        return EmojiService.get_emoji_pack_emoji_maps(emoji_pack_id)


api.add_resource(EmojiPackManageApi,"/emojipacks")
api.add_resource(EmojiManangeApi,"/emojis")
api.add_resource(EmojiMapsApi,"/emojis/<string:emoji_pack_id>/maps")